package com.fanly.weixin.netty.lock.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.fanly.weixin.netty.lock.entity.FgMessageData;
import com.fanly.weixin.netty.lock.service.DataParseService;
import com.fanly.weixin.utils.HexUtils;
import com.fanly.weixin.utils.SubStringUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * gb32960实时数据解析实现
 * @author D-BJ-144
 *
 */
@Slf4j
@Service
public class DataParseServiceImpl implements DataParseService {


	private static int total = 0;
	/**
	 * 实时数据解析并返回数据
	 * @param readDatas
	 */
    @Override
    public String realTimeDataParseAndPushData(ChannelHandlerContext ctx, String readDatas) throws Exception{
        try {
        	log.info("DataParseServiceImpl-realTimeDataParseAndPushData request data :" +readDatas);
        	if (StrUtil.isBlank(readDatas) || readDatas.length()<16) {
				log.error("DataParseServiceImpl-realTimeDataParseAndPushData request is empty or len less than 16 ");
        		return readDatas;
        	}
        	FgMessageData messageData = new FgMessageData();
        	String session = SubStringUtil.subStr(readDatas,0,8);
        	String cmd = SubStringUtil.subStr(readDatas,8,10);
        	String flag = SubStringUtil.subStr(readDatas,10,12);
        	String len = SubStringUtil.subStr(readDatas,12,16);
        	messageData.setSession(session);
        	messageData.setCmd(cmd);
        	messageData.setFlag(flag);
        	messageData.setLen(len);
        	String errorInfo = "00000000";
        	if ("00".equals(cmd)) {
				// 心跳
            	return readDatas;
            } else if ("01".equals(cmd)){
				// 错误数据
//            	return readDatas;
            } else if ("02".equals(cmd)) {
				//登录
            	String userName = HexUtils.convertHexToString(SubStringUtil.subStr(readDatas,16,272)).trim() ;
            	String password = HexUtils.convertHexToString(SubStringUtil.subStr(readDatas,272,400)).trim() ;
            	String version = HexUtils.convertHexToString(SubStringUtil.subStr(readDatas,400,readDatas.length())).trim() ;
            	String sessionId = HexUtils.addZeroForStr(String.format("%x", ++total), 8, 2) ;
//            	String sessionId = "d0050000";
            	messageData.setSession(sessionId);
            	messageData.setLen("4400");
            	messageData.setError("00000000");
            	String time = HexUtils.addZeroForStr(HexUtil.encodeHexStr(DateUtil.now()), 128, 2) ;
            	messageData.setTime(time);
            	StringBuffer pushData=new StringBuffer().append(messageData.getSession())
            			 .append(messageData.getCmd()).append(messageData.getFlag())
                         .append(messageData.getLen()).append(messageData.getError())
                         .append(messageData.getTime());

				// TODO 加入缓存
                return String.valueOf(pushData);
            } else if ("03".equals(cmd)) {
				// 退出 ， 服务器收到退出请求后，直接释放 SOCKET，不回复设备
            } else if ("04".equals(cmd)) {
				// 时间同步，设备发起  session\cmd\flag\len\error\time
            	return String.format("%s%s%s%s%s", session,cmd,flag,"4000",HexUtils.addZeroForStr(HexUtil.encodeHexStr(DateUtil.now()), 128, 2) );
            } else if ("05".equals(cmd)) {
				// 数据发送，双向
            	String businessData = SubStringUtil.subStr(readDatas,16,readDatas.length());
            	String header = SubStringUtil.subStr(businessData,0,4);
            	if (!"aabb".equalsIgnoreCase(header)) {
            		return readDatas;
            	}
            	messageData.setLen("2500");
				// 响应业务数据
            	StringBuilder data = new StringBuilder("aabb");
            	String businessCmd = SubStringUtil.subStr(businessData,8,10);
            	if ("81".equals(businessCmd)) {
					// 服务器查询设备应答（WIFI->服务端）
            	}
            } 
//        	HexUtils.getBCC(len);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return readDatas;
    }

	/**
	 * 初始化错误信息
	 * @param messageData
	 */
    private void initErrorMessageData(FgMessageData messageData) {
		
		
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
        String a = "4c464341483935570344d33303130303936";
        String newstr = new String(a.getBytes(Charset.defaultCharset()),"US-ASCII");
        String bcc = HexUtils.getBCC("4C46434148393657374D3330363032303101001E1508010A1228000A38393836303434393138313938303037363136370100");
        System.out.println(bcc);
        
        bcc = HexUtils.getBCC("20221206183102");
        System.out.println(bcc);
        System.out.println(HexUtil.encodeHexStr(DateUtil.now()));
        System.out.println(Integer.parseInt("32", 16));
        System.out.println(Integer.parseInt("d005", 16));
        System.out.println(HexUtils.hexStr2Int("00000001"));
        System.out.println(String.format("%x", 53253));
        System.out.println(HexUtil.decodeHexStr("323032322d31322d30372031313a32353a3530000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"));
        System.out.println(HexUtil.decodeHexStr("323032322d31322d30372031353a35393a3233000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"));
        String str = "9405000005002500aabb002082bea4f776eecfba2c07020412000010260000000000000000000000000000004f";
        String businessData = SubStringUtil.subStr(str,16,str.length());
        String cmd = SubStringUtil.subStr(businessData,8,10);
        System.out.println(businessData);
        System.out.println(cmd);
        
        
        String ss = "   111     ";
        System.out.println(ss.trim().length());
	}
}